package cn.darkhorse.mesadmin.controller.device;

import cn.darkhorse.common.config.DbTypeConfig;
import cn.darkhorse.common.config.WeatherConfig;
import cn.darkhorse.common.constant.CommonConstant;
import cn.darkhorse.device.iot.constant.IotConstant;
import cn.darkhorse.device.pojo.MesDevice;
import cn.darkhorse.device.service.LargeDataViewService;
import cn.darkhorse.device.service.MesDeviceService;
import cn.darkhorse.device.vo.MesWeatherVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 大屏控制类
 */
@RestController
@RequestMapping("/device/iotPointTable")
public class LargeViewController extends BaseController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private MesDeviceService mesDeviceService;
    @Resource
    private LargeDataViewService largeDataViewService;
    @Resource
    private DbTypeConfig dbTypeConfig;

    @RequestMapping("/getStatus")
    public AjaxResult getStatus(){
        Map<Object, Map<Object,Object>> listKey = getListKey(IotConstant.CACHE_MQTT_DATA_REAL_DATA);
        Map<Object, Object> data=new HashMap<>();
        Map<String,String> onlineMap=new HashMap<>();
        Map<String,String> statusMap=new HashMap<>();
        LambdaQueryWrapper<MesDevice> wrapper=new LambdaQueryWrapper<>();
        wrapper.isNotNull(MesDevice::getGatewayDeviceId);
        List<MesDevice> list = mesDeviceService.list(wrapper);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(MesDevice::getGatewayDeviceId, MesDevice::getName));
        //在线
        Integer onLineNum=0;
        //离线
        Integer offLineNum=0;
        //运行
        Integer runNum=0;
        //停止
        Integer stopNum=0;
        //急停
        Integer fastStopNum=0;
        for (Map.Entry<Object, Map<Object,Object>> entry : listKey.entrySet()) {
            String key=entry.getKey().toString();
            String dataDeviceId="history_"+key.replace(IotConstant.CACHE_MQTT_DATA_REAL_DATA,"");
            Map<Object,Object> value=entry.getValue();
            if(value.containsKey("DI0")){
                String di0 = value.get("DI0").toString().replace("\"", "");
                Integer status= Integer.valueOf(di0);
                if(status==1){
                    onLineNum+=1;
                    if(collect.containsKey(dataDeviceId)){
                        onlineMap.put(collect.get(dataDeviceId),"在线");
                    }
                }else{
                    offLineNum+=1;
                    if(collect.containsKey(dataDeviceId)){
                        onlineMap.put(collect.get(dataDeviceId),"离线");
                    }
                }
            }
            if(value.containsKey("DI1")){
                String di1 = value.get("DI1").toString().replace("\"", "");
                Integer status= Integer.valueOf(di1);
                if(status==1){
                    runNum+=1;
                    if(collect.containsKey(dataDeviceId)){
                        statusMap.put(collect.get(dataDeviceId),"运行");
                    }
                }
            }
            if(value.containsKey("DI2")){
                String di2 = value.get("DI2").toString().replace("\"", "");
                Integer status= Integer.valueOf(di2);
                if(status==1){
                    stopNum+=1;
                    if(collect.containsKey(dataDeviceId)){
                        statusMap.put(collect.get(dataDeviceId),"停止");
                    }
                }
            }
            if(value.containsKey("DI3")){
                String di3 = value.get("DI3").toString().replace("\"", "");
                Integer status= Integer.valueOf(di3);
                if(status==1){
                    fastStopNum+=1;
                    statusMap.put(collect.get(dataDeviceId),"急停");
                }
            }
        }
        data.put("onLineNum",onLineNum);
        data.put("offLineNum",offLineNum);
        data.put("runNum",runNum);
        data.put("stopNum",stopNum);
        data.put("fastStopNum",fastStopNum);
        data.put("onlineMap",onlineMap);
        data.put("statusMap",statusMap);
        return AjaxResult.success(data);
    }
    @RequestMapping("/getControl")
    public AjaxResult getControlDevice(){
        List<Map<String,String>> data=new ArrayList<>();
        String[] tables={"history_NBP_1000A","history_YSM_5028","history_T0M800","history_VMC1260"};
        LambdaQueryWrapper<MesDevice> wrapper=new LambdaQueryWrapper<>();
        wrapper.isNotNull(MesDevice::getGatewayDeviceId);
        List<MesDevice> list = mesDeviceService.list(wrapper);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(MesDevice::getGatewayDeviceId, MesDevice::getName));
        for (String table : tables) {
            String sql="select top 1 * from "+table+" order by id desc";
            if (dbTypeConfig.getType().equals(CommonConstant.DB_TYPE_MYSQL)) {
                sql="select  * from "+table+" order by id desc limit 1";
            }
            Map<String, Object> stringObjectMap = SqlRunner.db().selectOne(sql);
            Map<String,String> dataDetail=new HashMap<>();
            if(collect.containsKey(table)){
                dataDetail.put("name",collect.get(table) );
                if(null!=stringObjectMap){
                    if(stringObjectMap.containsKey("CurExePrgname")){
                        dataDetail.put("CurExePrgname",stringObjectMap.get("CurExePrgname").toString());
                    }else {
                        dataDetail.put("CurExePrgname","");
                    }
                    if(stringObjectMap.containsKey("RunTime1")){
                        dataDetail.put("RunTime1",stringObjectMap.get("RunTime1").toString());
                    }else {
                        dataDetail.put("RunTime1","");
                    }
                    if(stringObjectMap.containsKey("SPLoad")){
                        dataDetail.put("SPLoad",stringObjectMap.get("SPLoad").toString());
                    }else {
                        dataDetail.put("SPLoad","");
                    }
                }
                data.add(dataDetail);
            }
        }
        return AjaxResult.success(data);
    }


    /**
     * 天气
     * @return
     */
    @RequestMapping(value = "/weather",method = RequestMethod.POST)
    public AjaxResult getWeather(){
        MesWeatherVO vo=largeDataViewService.getWather(WeatherConfig.getLocation());
        return AjaxResult.success(vo);
    }

    /**
     * 获取所有的key
     */
    public Map<Object, Map<Object,Object>> getListKey(String prefix) {
        Map<Object, Map<Object,Object>> values=new HashMap<>();
        Set<String> keys = redisTemplate.keys(prefix+"*");
        keys.forEach(item->{
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(item);
            values.put(item,entries);
        });
        return values;
    }
}
